var redis = require('redis');
var express = require('express');
var app = express();

//这里建立了三个redis的客户端，为什么是3个呢？
//一个是发布，一个是订阅，一个是处理正常的req,res
//本来是想用订阅的client来处理的req,res,但是却报错
//后来查了以后才知道，原来如果此客户端订阅就不能下CRUD命令

var clientSub = redis.createClient(6379, 'localhost');
var clientPub = redis.createClient(6379, 'localhost');
var clientRes = redis.createClient(6379, 'localhost');

clientRes.on('ready', function(err){
    console.log('hello, i handle req/res');
});

clientPub.on('ready', function (err) {
    console.log('hello, i publish');
});

clientSub.on('ready', function (err) {
    console.log('hello, i subscribe');
});

clientSub.subscribe('channel1'); //订阅channel1

clientSub.on('subscribe', function (channel, count) {
    console.log(`got subscribe event: ${channel} and count is ${count}`);
    setInterval(()=>{
        clientPub.publish('channel1', `hi, i am channel one, message at ${new Date()}`);
    }, 2000); //每2秒钟发个消息
});

clientSub.on('connect', function () {
    clientSub.on('message', function (channel, message) {
        var response = `received message from ${channel}:${message}`; //订阅客户端接收到消息
        clientRes.lpush('myResponse', response,redis.print); //接收到消息以后，由req/res客户端来存储消息
    });
});

app.get('/', function (req, res) {
    clientRes.lrange('myResponse',0,-1, function(err, result){
        res.send(result);//拿出所有消息发到浏览器
    })  
})

app.listen(1338, function () {
    console.log('App listening on port 1338!');
});
